#coding=utf-8
# !/usr/bin/python
# -*- coding: utf-8 -*-

from dt import * # 引用主文件数据

class UpdateDataThread(QThread):
    _signal_update = pyqtSignal(str)  # 信号
    def __init__(self, parm, parent=None):
        super(UpdateDataThread, self).__init__(parent)
        self.is_exit = False
        self.parm = parm
        
    # 执行任务，任务完成时，发送信号    
    def run(self):
        while True:
            if self.parm.ser.isOpen():
                try:
                    if 1 == self.parm.dump_en:
                        buflen = self.parm.ser.in_waiting
                        blocklen = self.parm.highspeed.dt_framelen * 200 # 缓冲大于200帧时开始处理
                        if buflen > blocklen :
                            head = self.parm.ser.read(blocklen)
                            idx = self.parm.highspeed.find_head(head[0:])
                            self.parm.highspeed.parse_block(head[idx:])
                            self._signal_update.emit("0") # 发送信号给槽函数
                            self.parm.data_num_received+= blocklen
                            if self.parm.data_num_received > 1024*1024:
                                content = "{:.1f}".format(self.parm.data_num_received/1024/1024) + "MB"
                            elif self.parm.data_num_received > 1024:
                                content = "{:.1f}".format(self.parm.data_num_received/1024)+ "KB"
                            else:
                                content = "{:.1f}".format(self.parm.data_num_received)+ "B"
                            self.parm.edit6.setText(content)   
                    else:
                        buflen = self.parm.ser.in_waiting
                        if buflen >= 64 :
                            a = self.parm.ser.read(buflen)
                            data = np.frombuffer(a, dtype=np.uint8)
                            res = self.parm.devsta.decode(data)   
                            if res == 1:
                               self._signal_update.emit("1")
                except:
                    time.sleep(0.1)
            time.sleep(0.1)
